clear
discard
set more off

adopath ++ "./ado/"

******************
*** Parameters ***
******************

local file_name "./input/consensus_dataset.csv"  // Data file
local output_folder "./output/horizons" // Output directory
local K = 4 // Number of lags to include when calculating local projections
local L = 16 // Number of IRF coefficients to estimate
local alpha = 0.05 // Significance level
local L_NW = 5 // Number of lags for calculating Newey-West standard errors

*************************************
*** Import data and set data type ***
*************************************

import delimited using `file_name', case(preserve)
rename DATE Date

gen qtr = quarterly(Date,"YQ")
format qtr %tq
tsset qtr // Set to time series

********************************
*** Generate forecast errors ***
********************************

gen Efor_Step2 = Realiz1 - SPFfor_Step2
gen Efor_Step3 = Realiz1 - SPFfor_Step3
gen Efor_Step4 = Realiz1 - SPFfor_Step4

* There is a missing forecast for Q4-ahead forecast
* in 1975:Q3, replace with value for Q3-ahead forecast
replace SPFfor_Step5 = SPFfor_Step4 if SPFfor_Step5 == . & Date == "1975:03"

gen Efor_Step5 = Realiz1 - SPFfor_Step5

****************************************
*** Set same sample for all horizons ***
****************************************

drop if qtr <= tq(1971q1)

***********************************
*** Calculate local projections ***
***********************************

estimate_IRF_LP Efor_Step2, k(`K') l(`L') alpha(`alpha') min_lags_NW(`L_NW') 
matrix IRF_LP_1Q_ahead = e(s)

estimate_IRF_LP Efor_Step3, k(`K') l(`L') alpha(`alpha') min_lags_NW(`L_NW') 
matrix IRF_LP_2Q_ahead = e(s)

estimate_IRF_LP Efor_Step4, k(`K') l(`L') alpha(`alpha') min_lags_NW(`L_NW') 
matrix IRF_LP_3Q_ahead = e(s)

estimate_IRF_LP Efor_Step5, k(`K') l(`L') alpha(`alpha') min_lags_NW(`L_NW') 
matrix IRF_LP_4Q_ahead = e(s)

* Clean up
shell rm -r `output_folder'
shell mkdir -p ./output
shell mkdir `output_folder'

* Save estimated IRFs
mat2txt, matrix(IRF_LP_1Q_ahead) saving(`output_folder'/IRF_LP_1Q_ahead.txt)
mat2txt, matrix(IRF_LP_2Q_ahead) saving(`output_folder'/IRF_LP_2Q_ahead.txt)
mat2txt, matrix(IRF_LP_3Q_ahead) saving(`output_folder'/IRF_LP_3Q_ahead.txt)
mat2txt, matrix(IRF_LP_4Q_ahead) saving(`output_folder'/IRF_LP_4Q_ahead.txt)
